package com.atguigu.gulimall.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResponVo;
import com.atguigu.gulimall.seckill.feign.CouponFeignService;
import com.atguigu.gulimall.seckill.feign.ProductFeignService;
import com.atguigu.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.seckill.service.SeckillService;
import com.atguigu.gulimall.seckill.to.SeckillSkuRedisTo;
import com.atguigu.gulimall.seckill.vo.SeckSessionWithSkus;
import com.atguigu.gulimall.seckill.vo.SeckillSkuVo;
import com.atguigu.gulimall.seckill.vo.SkuInfoVo;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author ming
 * @create 2022/5/13
 * @description:
 */
@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {
    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";
    private final String SKUKILL_CACHE_PREFIX = "seckill:skus";
    private  final String SKU_STOCK_SEMAPHORE="seckill:stock:";//+商品随机码
    @Autowired
    private RabbitTemplate rebbitsTemplate;
    @Autowired
    private RedissonClient redissonClient;
    @Override
    public void uploadSeckillLate3Day() {
        //去扫描最近三天要参与秒杀的活动
        R r = couponFeignService.getLateste3Day();
        if(r.getCode()==0){
            List<SeckSessionWithSkus> sessionData = r.getData(new TypeReference<List<SeckSessionWithSkus>>() {
            });
            //缓存到redis
            /**
             * 1.保存活动信息
             * 2.保存活动关联的商品信息
             */
            if (CollectionUtils.isNotEmpty(sessionData)) {
                saveSessionInfos(sessionData);
                saveSessionSkuInfos(sessionData);
            }

        }
    }

    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        //确定当前时间属于哪个秒杀场次
        long time = new Date().getTime();
        Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
        for (String key : keys) {
            String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
            String[] s = replace.split("_");
            long start = Long.parseLong(s[0]);
            long end = Long.parseLong(s[1]);
            if(time>=start && time <=end){
                //获取这个秒杀场次需要的所有商品信息
                List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                BoundHashOperations<String, String, String> hasOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                List<String> list = hasOps.multiGet(range);
                if(CollectionUtils.isNotEmpty(list)){
                    List<SeckillSkuRedisTo> collect = list.stream().map(item -> {
                        SeckillSkuRedisTo redis = JSON.parseObject((String) item, SeckillSkuRedisTo.class);
                        return redis;
                    }).collect(Collectors.toList());
                    return collect;
                }
                break;
            }
        }

        return null;
    }

    @Override
    public SeckillSkuRedisTo getSkuSkillInfo(Long skuId) {
        //找到所有需要参与秒杀的信息key
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = ops.keys();
        if (CollectionUtils.isNotEmpty(keys)) {
            String reg = "\\d_"+skuId;
            for (String key : keys) {
                if (Pattern.matches(reg,key)) {
                    String json = ops.get(key);
                    SeckillSkuRedisTo seckRedisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
                    long current = new Date().getTime();
                    Long startTime = seckRedisTo.getStartTime();
                    Long endTime = seckRedisTo.getEndTime();
                    if(current>=startTime && current<=endTime) {
                        return seckRedisTo;
                    }
                    seckRedisTo.setRandomCode(null);
                    return seckRedisTo;
                }
            }
        }
        return null;
    }

    @Override
    public String kill(String killId, String key, Integer num) {
        MemberResponVo memberResponVo = LoginUserInterceptor.loginUser.get();
        //获取当前秒杀的详细信息
        BoundHashOperations<String, String, String> hasOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String json = hasOps.get(killId);
        if(StringUtils.isEmpty(json)){
            return null;
        }
        SeckillSkuRedisTo redis = JSON.parseObject(json, SeckillSkuRedisTo.class);
        //校验合法性
        Long startTime = redis.getStartTime();
        Long endTime = redis.getEndTime();
        long current = new Date().getTime();
        long ttl = endTime - startTime;
        //校验时间
        if(!(current>=startTime && current<=endTime)){
            return null;
        }
        //校验随机码和商品id
        String randomCode = redis.getRandomCode();
        String skuId = redis.getPromotionSessionId()+"_"+redis.getSkuId();
        if(!(randomCode.equals(key)&&killId.equals(skuId))){
            return null;
        }
        //验证购物数量是否合理
        if (redis.getSeckillLimit()<num) {
            return null;
        }
        //验证此人是否购买过了 幂等性,如果秒杀成功就去redis去占位 userId_SessionId_skuId
        String redisKey = memberResponVo.getId()+"_"+skuId;
        //自动过期
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
        if(!aBoolean){
            return null;
        }
        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
        if (!semaphore.tryAcquire(num)){
            return null;
        }
        //秒杀成功
        //快速下单.发送一个mq消息
        String timeId = IdWorker.getTimeId();
        SeckillOrderTo orderTo = new SeckillOrderTo();
        orderTo.setOrderSn(timeId);
        orderTo.setMemberId(memberResponVo.getId());
        orderTo.setNum(num);
        orderTo.setPromotionSessionId(redis.getPromotionSessionId());
        orderTo.setSkuId(redis.getSkuId());
        orderTo.setSeckillPrice(redis.getSeckillPrice());
        rebbitsTemplate.convertAndSend("order-event-exchange","order.seckill.order",orderTo);
        return timeId;


    }

    private void saveSessionInfos(List<SeckSessionWithSkus>  sessions){
       sessions.stream().forEach(session->{
           Long startTime = session.getStartTime().getTime();
           Long endTime = session.getEndTime().getTime();
           String key = SESSIONS_CACHE_PREFIX + startTime+"_"+endTime;
           Boolean hasKey = redisTemplate.hasKey(key);
           //缓存活动信息
           if(!hasKey) {
           List<String> collect = session.getRelationSkus().stream().map(item->item.getPromotionSessionId()+"_"+item.getSkuId().toString()).collect(Collectors.toList());
               redisTemplate.opsForList().leftPushAll(key,collect);
           }
       });
    }
    private void saveSessionSkuInfos(List<SeckSessionWithSkus>  sessions){

        sessions.stream().forEach(session->{
            //准备hash操作
            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            session.getRelationSkus().stream().forEach(seckillSkuVo->{
                //随机码
                String token = UUID.randomUUID().toString().replace("-", "");
                if (!ops.hasKey(seckillSkuVo.getPromotionSessionId()+"_"+seckillSkuVo.getSkuId().toString())) {
                    SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();
                    /**缓存商品
                     * 1.sku基本西信息
                     * 2.sku的秒杀信息
                     * 3
                     */
                    //sku基本信息
                    R skuInfo = productFeignService.getSkuInfo(seckillSkuVo.getSkuId());
                    //sku的秒杀信息
                    BeanUtils.copyProperties(seckillSkuVo,redisTo);
                    if(skuInfo.getCode()==0){
                        SkuInfoVo info = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {});
                        log.info("********远程查询skuinfo:{}",skuInfo);
                        redisTo.setSkuInfo(info);
                    }


                    //设置当前商品的秒杀时间信息
                    redisTo.setStartTime(session.getStartTime().getTime());
                    redisTo.setEndTime(session.getEndTime().getTime());

                    redisTo.setRandomCode(token);
                    String s = JSON.toJSONString(redisTo);
                    log.info("redisTo:{}",redisTo);
                    ops.put(seckillSkuVo.getPromotionSessionId().toString()+"_"+seckillSkuVo.getSkuId().toString(),s);
                    //如果当前这个场次的商品的库存信息已经上架就不需要商家
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    //商品数量可以作为分布式信号量
                    semaphore.trySetPermits(seckillSkuVo.getSeckillCount());
                }
                
            });
        });

    }
}
